import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({
  showSpinner: false// 是否显示加载ico
}) // NProgress Configuration
//白名单
const whiteList = ['/login'] // no redirect whitelist
//路由守卫
//to：进入到哪个路由去
// from：从哪个路由离开
// next：路由的控制参数，常用的有next(true)和next(false)
router.beforeEach(async(to, from, next) => {
  // 进度条开启
  NProgress.start()

  // 页面标题
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  //判断是否已经登录
  if (hasToken) {
    //如果已经登录 则判断是否前往登录页面
    if (to.path === '/login') {
      // 如果是 则重定向进入主页面
      next({ path: '/' })
      // 进度条关闭
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      //判断是否有用户信息
      if (hasGetUserInfo) {
        //有则下一步正常跳转
        next()
      } else {
        try {
          //没有就获取用户信息
          await store.dispatch('user/getInfo')

          next()
        } catch (error) {
          //出错则移除token 重定向到login登录
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    //未登录情况

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      //判断访问的页面是否在白名单中 有则正常跳转
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      //没有的话 重定向到登录页面
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  //关闭进度条
  NProgress.done()
})
